package com.policyCloud.policyGateway.security;

import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.annotation.PostConstruct;
import java.util.*;

import static java.util.stream.Collectors.toList;

@Data
//@Component
public class CheckUrlPer {

    private static Map<String, Collection<String>> cheakPermitUrlPattern;
    private PathMatcher matcher;

    @PostConstruct
    public void init() {
        this.cheakPermitUrlPattern = new HashMap<>();
        Collection<String> atts = new ArrayList<>();
        atts.add("Perm_增");
        cheakPermitUrlPattern.put("/api/ssoUser/page", atts);
    }


    public Collection<String> checkIsPerUrl(String url) {
        for (Iterator<Map.Entry<String, Collection<String>>> iter = cheakPermitUrlPattern.entrySet().iterator(); iter.hasNext(); ) {
            Map.Entry<String, Collection<String>> entry = iter.next();
            String key = entry.getKey();
            this.matcher= new AntPathMatcher();
            if (matcher.match(key, url)) {
                return cheakPermitUrlPattern.get(url);
            }
        }
        return new ArrayList<>();
    }

    public boolean checkHavePerByUrl(Collection<String> need,Collection<String> have) {
        List<String> intersection = need.stream().filter(item -> have.contains(item)).collect(toList());
        if(CollectionUtils.isEmpty(intersection)){
            return false;
        }
        return true;
    }

    public boolean checkHavePer(Collection<String> roleAndPerList,String gotoUrl) {
        Collection<String> need= checkIsPerUrl(gotoUrl);
        if(CollectionUtils.isEmpty(need)){
            return true;
        }else{
            return checkHavePerByUrl(need,roleAndPerList);
        }
    }

}
